<?php

namespace common\widgets\grid;

use Yii;
use Closure;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;

/**
 * CheckboxColumn displays a column of checkboxes in a grid view.
 *
 * To add a CheckboxColumn to the [[GridView]], add it to the [[GridView::columns|columns]] configuration as follows:
 *
 * ```php
 * 'columns' => [
 *     // ...
 *     [
 *         'class' => 'yii\grid\CheckboxColumn',
 *         // you may configure additional properties here
 *     ],
 * ]
 * ```
 *
 * Users may click on the checkboxes to select rows of the grid. The selected rows may be
 * obtained by calling the following JavaScript code:
 *
 * ```javascript
 * var keys = $('#grid').yiiGridView('getSelectedRows');
 * // keys is an array consisting of the keys associated with the selected rows
 * ```
 *
 * For more details and usage information on CheckboxColumn, see the [guide article on data widgets](guide:output-data-widgets).
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class CheckboxColumn extends \yii\grid\CheckboxColumn {

    public $model;
    public $label = null;

    /**
     * @var string the css class that will be used to find the checkboxes.
     * @since 2.0.9
     */
    public $customType = 'switch';

    /**
     * @var string the css class that will be used to find the checkboxes.
     * @since 2.0.9
     */
    public $customCssClass = 'custom-control-input';

    /**
     * @var string the css class that will be used to find the checkboxes.
     * @since 2.0.9
     */
    public $checkAllOptions = [
//        'id' => 'select-on-check-all',
    ];
    public $clientScriptAsset;

    public function getCheckBoxName() {
        if ($this->model) {
            return Html::getInputName($this->model, $this->name);
        }
        return $this->name;
    }

    public function getCheckBoxId($key) {
        if ($this->model) {
            return Html::getInputId($this->model, $this->name . '[' . $key . ']');
        }
        return 'select-on-check-' . $key;
    }

    /**
     * Renders the header cell content.
     * The default implementation simply renders [[header]].
     * This method may be overridden to customize the rendering of the header cell.
     * @return string the rendering result
     */
    protected function renderHeaderCellContent() {
        if ($this->header !== null || !$this->multiple) {
            return parent::renderHeaderCellContent();
        }
        $options = $this->checkAllOptions;
        if (!isset($options['id'])) {
            $options['id'] = 'select-on-check-all';
        }
        Html::addCssClass($options, [
            $this->customCssClass,
            'select-on-check-all'
        ]);
        $labelText = ArrayHelper::remove($options, 'label', '全部');
        $label = Html::label($labelText, $options['id'], [
            'class' => 'custom-control-label'
        ]);
        $checkbox = Html::checkbox($this->getHeaderCheckBoxName(), false, $options);
        return Html::tag('div', $checkbox . $label, [
            'class' => 'custom-control custom-' . $this->customType
        ]);
    }

    protected function renderFooterCellContent() {
        if ($this->footer !== null || !$this->multiple) {
            return parent::renderFooterCellContent();
        }
        return Html::checkbox($this->getHeaderCheckBoxName(), false, ['class' => 'select-on-check-all']);
    }

    /**
     * {@inheritdoc}
     */
    protected function renderDataCellContent($model, $key, $index) {
        if ($this->content !== null) {
            return parent::renderDataCellContent($model, $key, $index);
        }
        if ($this->checkboxOptions instanceof Closure) {
            $options = call_user_func($this->checkboxOptions, $model, $key, $index, $this);
        } else {
            $options = $this->checkboxOptions;
        }
        if (!isset($options['value'])) {
            $options['value'] = is_array($key) ? Json::encode($key) : $key;
        }
        if ($this->customCssClass !== null) {
            Html::addCssClass($options, $this->customCssClass);
        }
        if (!isset($options['id'])) {
            $options['id'] = $this->getCheckBoxId($key); // 'select-on-check-' . $key;
        }
        $labelText = ArrayHelper::remove($options, 'label');

        $label = Html::label($labelText, $options['id'], [
            'class' => 'custom-control-label'
        ]);

        $checkbox = Html::checkbox($this->getCheckBoxName(), !empty($options['checked']), $options);

        return Html::tag('div', $checkbox . $label, [
            'class' => 'custom-control custom-' . $this->customType
        ]);
    }

    /**
     * Registers the needed JavaScript.
     * @since 2.0.8
     */
    public function registerClientScript() {
        $view = $this->grid->getView();
        $id = $this->grid->options['id'];
        $options = Json::encode([
            'name' => $this->getCheckBoxName(),
            'class' => $this->cssClass,
            'multiple' => $this->multiple,
            'checkAll' => $this->grid->showHeader ? $this->getHeaderCheckBoxName() : null,
        ]);
        $view->registerJs("jQuery('#$id').yiiGridView('setSelectionColumn', $options);");

        if ($this->clientScriptAsset) {
            try {
                $assetClass = ArrayHelper::getValue($this->clientScriptAsset, 'class');
                $assetBundle = Yii::createObject($assetClass);
                if ($assetBundle && $assetBundle instanceof \yii\web\AssetBundle) {
                    $assetBundle::register($view);
                }
            } catch (InvalidConfigException $exc) {
                Yii::error($exc->getTraceAsString());
            }
            $handles = ArrayHelper::getValue($this->clientScriptAsset, 'handles', []);
            $id = $this->grid->options['id'];
            $options = Json::encode([
                'name' => $this->name,
                'class' => $this->cssClass,
                'multiple' => $this->multiple,
                'checkAll' => $this->grid->showHeader ? $this->getHeaderCheckBoxName() : null,
            ]);
            foreach ($handles as $handle) {
                $view->registerJs("jQuery('#$id').yiiGridColumn('$handle', $options);");
            }
        }
    }

}
